package com.hippo.core.ui.compose.main

import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.hippo.core.ui.components.BottomTabBar
import com.hippo.core.ui.compose.home.HomeScreen
import com.hippo.core.ui.compose.mine.MineScreen
import com.hippo.core.ui.compose.spt.SptScreen
import com.hippo.core.ui.theme.HippoTheme
import com.hippo.core.vm.HomeVM
import com.hippo.core.vm.MainVM
import kotlinx.coroutines.launch

@Composable
fun MainScreen(vm: MainVM = viewModel(), navController: NavController) {

    val pagerState = rememberPagerState { 3 }
    val homeVM: HomeVM = viewModel()

    var uiState = vm.uiState


    LaunchedEffect(uiState) {
        pagerState.animateScrollToPage(uiState.tabIndex)
    }

    Column {

        HorizontalPager(
            state = pagerState,
            userScrollEnabled = false,
            modifier = Modifier.weight(1F)
        ) { page ->
            when (page) {
                0 -> HomeScreen(navController,homeVM)
                1 -> SptScreen(navController)
                2 -> MineScreen(navController)
            }
        }

        BottomTabBar(
            checkIndex = uiState.tabIndex,
            onItemChecked = { index ->
                Log.i("sss", "MainScreen: $index")
                vm.updateState(uiState.copy(tabIndex = index))
            }
        )
    }

}


@Preview(showBackground = true)
@Composable
private fun MainScreenPreview() {
    HippoTheme {
        MainScreen(
            navController = rememberNavController()
        )
    }
}
